package com.bjb.vr.auth.security;

import com.bjb.vr.common.result.CommonResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 匿名用户访问无权限资源时的异常处理
 *
 * @version 1.0.0
 * @author: HuJingBo
 * @time: 2022/4/7 17:59
 */
@Slf4j
@Component
public class RequestAuthenticationEntryPointHandler implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.error("无权限访问资源！请求路径：{}", request.getRequestURI());
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(new ObjectMapper().writeValueAsString(CommonResult.Fail("无权限访问资源，请先登录！")));
    }
}
